/**
 * Copyright (C) 2004-2009 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.onlyxiahui.of.muc.iq;

import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.openfire.muc.MultiUserChatService;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.Presence;

import com.onlyxiahui.of.muc.dao.RoomDAO;

public class IQRoomHandler extends IQHandler {

	private IQHandlerInfo info;
	private String serverName;

	private static final String MODULE_NAME = "Joined Room Handler";
	private static final String NAME_SPACE = "http://www.jivesoftware.org/protocol/joinde#room";
	private static final String NAME_KEY = "rooms";

	public IQRoomHandler() {
		super(MODULE_NAME);
		info = new IQHandlerInfo(NAME_KEY, NAME_SPACE);
	}

	@Override
	public IQ handleIQ(IQ packet) throws UnauthorizedException {
		IQ result = IQ.createResultIQ(packet);
		String userJid = packet.getFrom().toBareJID();// .getNode();
		// String username = packet.getFrom().getNode();
		JID jid = packet.getFrom();
		if (!serverName.equals(packet.getFrom().getDomain()) || userJid == null) {
			result.setChildElement(packet.getChildElement().createCopy());
			result.setError(PacketError.Condition.not_allowed);
			return result;
		}
		String domain = "@conference." + serverName;
		Element rooms = result.setChildElement(NAME_KEY, NAME_SPACE);
		MultiUserChatService service = XMPPServer.getInstance().getMultiUserChatManager()
				.getMultiUserChatService("conference");

		// List<RoomInfo> list = RoomDAO.getRoomInfoList(username);
		// for (RoomInfo ri : list) {
		// String roomName = ri.getName();
		// String roomPassword = ri.getRoomPassword();
		//
		// MUCRoom mucroom = service.getChatRoom(roomName);
		//
		// if (null != mucroom) {
		// // mucroom=service.
		//
		// String roomJid = roomName + domain;
		//
		// String toId = roomJid + "/" + username;
		// // JID toJID = new JID(roomJid);
		// Presence joinPresence = new Presence();
		// joinPresence.setID("join-room");
		// joinPresence.setFrom(jd);
		// joinPresence.setTo(toId);
		// Element e =
		// joinPresence.addChildElement("x","http://jabber.org/protocol/muc");
		// Element p = e.addElement("password");
		// if (null != roomPassword && !roomPassword.isEmpty()) {
		// p.setText(roomPassword);
		// }
		//
		// Element h =e.addElement("history");
		// h.addAttribute("maxchars", "0");
		// h.addAttribute("maxstanzas", "0");
		// h.addAttribute("seconds", "0");
		// //h.addAttribute("since", "0");
		// // joinPresence.s
		// service.processPacket(joinPresence);
		// rooms.addElement("roomJid").setText(mucroom.getJID().toBareJID());
		// }
		// }

		// PresenceManager pm=XMPPServer.getInstance().getPresenceManager();
		// long last=pm.getLastActivity(user)
		// String dateTime = null;
		// long time = UserDAO.getOfflineTimeString(userJid);
		// if (time > 0) {
		// Date date = new Date(time);
		// DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
		// dateTime = df.format(date) + "Z";
		// }

		List<Map<String, String>> list = RoomDAO.getMUCInfo(userJid);
		if (list != null && !list.isEmpty()) {
			for (Map<String, String> map : list) {
				// String serviceId = map.get("serviceId");
				String roomName = map.get("name");
				// String roomId = map.get("roomId");
				String nickname = map.get("nickname");
				String roomPassword = map.get("roomPassword");

				nickname = (null == nickname || nickname.isEmpty()) ? userJid : nickname;

				MUCRoom mucroom = service.getChatRoom(roomName);

				if (null != mucroom) {
					// mucroom=service.
					//long roomId = mucroom.getID();
					String roomJid = roomName + domain;

					String toId = roomJid + "/" + nickname;
					// JID toJID = new JID(roomJid);
					Presence joinPresence = new Presence();
					joinPresence.setID("join-room");
					joinPresence.setFrom(jid);
					joinPresence.setTo(toId);
					Element e = joinPresence.addChildElement("x", "http://jabber.org/protocol/muc");
					Element p = e.addElement("password");
					if (null != roomPassword && !roomPassword.isEmpty()) {
						p.setText(roomPassword);
					}

					Element h = e.addElement("history");

					// if (null != dateTime && !dateTime.isEmpty()) {
					// h.addAttribute("since", dateTime);
					// } else {
					h.addAttribute("maxchars", "0");
					h.addAttribute("maxstanzas", "0");
					h.addAttribute("seconds", "0");
					// }
					service.processPacket(joinPresence);
					rooms.addElement("roomJid").setText(mucroom.getJID().toBareJID());
				}
			}

		}
		return result;
	}

	@Override
	public IQHandlerInfo getInfo() {
		return info;
	}

	@Override
	public void initialize(XMPPServer server) {
		super.initialize(server);
		serverName = server.getServerInfo().getXMPPDomain();
	}

	// public void addOldMessage(String senderJID, String nickname, Date sentDate,
	// String subject,String body, String stanza)
	// {
	// Message message = new Message();
	// message.setType(Message.Type.groupchat);
	// if (stanza != null) {
	// // payload initialized as XML string from DB
	// SAXReader xmlReader = new SAXReader();
	// xmlReader.setEncoding("UTF-8");
	// try {
	// Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
	// for (Element child : (List<Element>)element.elements()) {
	// Namespace ns = child.getNamespace();
	// if (ns == null || ns.getURI().equals("jabber:client") ||
	// ns.getURI().equals("jabber:server")) {
	// continue;
	// }
	// Element added = message.addChildElement(child.getName(),
	// child.getNamespaceURI());
	// if (!child.getText().isEmpty()) {
	// added.setText(child.getText());
	// }
	// for (Attribute attr : (List<Attribute>)child.attributes()) {
	// added.addAttribute(attr.getQName(), attr.getValue());
	// }
	// for (Element el : (List<Element>)child.elements()) {
	// added.add(el.createCopy());
	// }
	// }
	// if (element.attribute("id") != null) {
	// message.setID(element.attributeValue("id"));
	// }
	// } catch (Exception ex) {
	// Log.error("Failed to parse payload XML", ex);
	// }
	// }
	// message.setSubject(subject);
	// message.setBody(body);
	// // Set the sender of the message
	// if (nickname != null && nickname.trim().length() > 0) {
	// JID roomJID = room.getRole().getRoleAddress();
	// // Recreate the sender address based on the nickname and room's JID
	// message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname,
	// true));
	// }
	// else {
	// // Set the room as the sender of the message
	// message.setFrom(room.getRole().getRoleAddress());
	// }
	//
	// // Add the delay information to the message
	// Element delayInformation = message.addChildElement("delay",
	// "urn:xmpp:delay");
	// delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate));
	// if (room.canAnyoneDiscoverJID()) {
	// // Set the Full JID as the "from" attribute
	// delayInformation.addAttribute("from", senderJID);
	// }
	// else {
	// // Set the Room JID as the "from" attribute
	// delayInformation.addAttribute("from",
	// room.getRole().getRoleAddress().toString());
	// }
	// historyStrategy.addMessage(message);
	// }
	// private void sendOfflineMessage() {
	//
	// }
}
